
package com.gitee.jmash.oidc.web.controller;

import com.gitee.jmash.common.event.SafeEvent;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.event.Event;
import jakarta.inject.Inject;
import jakarta.mvc.Controller;
import jakarta.mvc.MvcContext;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Context;
import java.io.IOException;
import java.security.Principal;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * 登出.
 *
 * @author CGD
 *
 */
@Path("logout")
@Controller
@RequestScoped
public class LogoutController {

  @Inject
  private MvcContext mvc;
  /** 安全日志. */
  @Inject
  Event<SafeEvent> event;

  /** logout. */
  @GET
  public String execute(@QueryParam("backurl") String backurl, @Context HttpServletResponse resp)
      throws IOException {
    // 登出
    Subject subject = SecurityUtils.getSubject();
    if (subject.isAuthenticated()) {
      // 登出安全日志
      Principal p=(Principal)subject.getPrincipal();
      event.fireAsync(SafeEvent.logout(p.getName()));
    }
    subject.logout();
    // 重新创建Session.
    subject.getSession(true);

    // Redirect backurl.
    if (StringUtils.isNotBlank(backurl)) {
      resp.sendRedirect(backurl);
      return null;
    } else {
      resp.sendRedirect(mvc.uri("DefaultController#execute").toString());
      return null;
    }
  }

}
